import * as vscode from 'vscode';
import { simpleGit, SimpleGit } from 'simple-git';
import { getZhipuAI } from './zhipuAI';

export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand('ai-git-copilot.generateMessage', async () => {
        try {
            // Get the Git SCM input box
            const gitExtension = vscode.extensions.getExtension('vscode.git');
            if (!gitExtension) {
                vscode.window.showErrorMessage('Git extension not found');
                return;
            }

            const git = gitExtension.exports.getAPI(1);
            const repo = git.repositories[0];
            
            if (!repo) {
                vscode.window.showErrorMessage('No Git repository found');
                return;
            }

            // Get workspace folder for git operations
            const workspaceFolders = vscode.workspace.workspaceFolders;
            if (!workspaceFolders) {
                vscode.window.showErrorMessage('没有打开的工作区');
                return;
            }

            const gitClient: SimpleGit = simpleGit(workspaceFolders[0].uri.fsPath);
            
            // Get current branch name
            const branchResult = await gitClient.branch();
            const currentBranch = branchResult.current;
            
            // First try to get staged changes
            let diff = await gitClient.raw(['diff', '--cached']);
            console.log(diff);
            // Check if there are staged changes
            if (!diff) {
                const hasUnstagedChanges = await gitClient.raw(['diff']);
                if (hasUnstagedChanges) {
                    vscode.window.showWarningMessage('请先暂存要提交的更改（git add）');
                } else {
                    vscode.window.showErrorMessage('没有检测到任何更改');
                }
                return;
            }

            // Get available prefixes from configuration
            const config = vscode.workspace.getConfiguration('ai-git-copilot');
            const defaultPrefixes = [
                'feat: ✨ 新功能',
                'fix: 🐛 修复',
                'docs: 📚 文档',
                'style: 💎 格式',
                'refactor: ♻️ 重构',
                'test: 🚨 测试',
                'chore: 🔧 构建'
            ];
            const prefixes = config.get<string[]>('prefixes', defaultPrefixes);

            // Show quick pick to select prefix
            const selectedPrefix = await vscode.window.showQuickPick(prefixes, {
                placeHolder: '选择提交类型'
            });

            if (selectedPrefix) {
                // Extract the prefix without emoji
                const prefix = selectedPrefix.split(':')[0] + ':';

                // Process with ZhipuAI
                const zhipuAI = getZhipuAI();

                vscode.window.withProgress({
                    location: vscode.ProgressLocation.Notification,
                    title: "正在使用 AI 生成提交消息...",
                    cancellable: false
                }, async () => {
                    try {
                        // Generate AI message based on the diff
                        const aiMessage = await zhipuAI.generateCommitMessage(diff, prefix);

                        // Extract fix type from branch name (if any)
                        let fixType = '';
                        const fixMatch = currentBranch.match(/(?:fix|bug|hotfix)[/-](\d+)/i);
                        if (fixMatch) {
                            fixType = `[#${fixMatch[1]}]`;
                        }
                        
                        // Combine branch name, prefix, fix type and AI-generated message
                        const finalMessage = `${currentBranch}: ${prefix} ${fixType}${fixType ? ' ' : ''}${aiMessage}`;
                        
                        // Update the input box
                        repo.inputBox.value = finalMessage;
                        
                        vscode.window.showInformationMessage('AI 提交消息生成完成');
                    } catch (error) {
                        vscode.window.showErrorMessage('AI 生成提交消息失败');
                    }
                });
            }
        } catch (error) {
            vscode.window.showErrorMessage('执行命令时发生错误');
        }
    });

    context.subscriptions.push(disposable);
}

export function deactivate() {}
